<template>
  <div class="blocked-tasks-container">
    <h1 class="page-title">阻塞任务</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="blocked-content">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="6">
          <el-select v-model="filters.project" placeholder="按项目筛选" clearable style="min-width: 180px;">
            <el-option
              v-for="item in projectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.priority" placeholder="按优先级筛选" clearable style="min-width: 160px;">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.blockType" placeholder="按阻塞类型筛选" clearable style="min-width: 180px;">
            <el-option label="依赖" value="dependency" />
            <el-option label="资源" value="resource" />
            <el-option label="技术" value="technical" />
            <el-option label="决策" value="decision" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="filters.search"
            placeholder="搜索任务名称"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>

      <div class="stats-row">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-value">{{ stats.total }}</div>
              <div class="stat-label">总阻塞任务</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card high-priority">
              <div class="stat-value">{{ stats.highPriority }}</div>
              <div class="stat-label">高优先级</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card long-blocked">
              <div class="stat-value">{{ stats.longBlocked }}</div>
              <div class="stat-label">阻塞超过7天</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card resolved-today">
              <div class="stat-value">{{ stats.resolvedToday }}</div>
              <div class="stat-label">今日已解决</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <div class="tasks-table">
        <el-table
          :data="filteredTasks"
          style="width: 100%"
          :default-sort="{ prop: 'blockDuration', order: 'descending' }"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="任务名称" min-width="200">
            <template #default="scope">
              <router-link :to="`/tasks/${scope.row.id}`" class="task-link">
                {{ scope.row.title }}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column prop="project" label="所属项目" width="150" />
          <el-table-column prop="assignee" label="负责人" width="120" />
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="scope">
              <el-tag :type="getPriorityType(scope.row.priority)" size="small">
                {{ scope.row.priority }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="blockType" label="阻塞类型" width="120">
            <template #default="scope">
              <el-tag :type="getBlockTypeColor(scope.row.blockType)" effect="dark" size="small">
                {{ getBlockTypeText(scope.row.blockType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="blockReason" label="阻塞原因" min-width="200" />
          <el-table-column prop="blockDate" label="阻塞时间" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.blockDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="blockDuration" label="阻塞天数" width="100" sortable>
            <template #default="scope">
              <span :class="getDurationClass(scope.row.blockDuration)">
                {{ scope.row.blockDuration }}天
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="success" size="small" @click="resolveTask(scope.row)">解除阻塞</el-button>
              <el-button type="primary" size="small" @click="viewDetails(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 解除阻塞对话框 -->
    <el-dialog v-model="resolveDialogVisible" title="解除阻塞" width="500px">
      <el-form :model="resolveForm" label-position="top">
        <el-form-item label="解决方案" required>
          <el-input
            v-model="resolveForm.solution"
            type="textarea"
            :rows="4"
            placeholder="请描述如何解决了这个阻塞问题"
          />
        </el-form-item>
        <el-form-item label="关联人员">
          <el-select
            v-model="resolveForm.relatedUsers"
            multiple
            placeholder="选择参与解决问题的人员"
            style="width: 100%;"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="后续行动">
          <el-input
            v-model="resolveForm.nextSteps"
            type="textarea"
            :rows="2"
            placeholder="需要采取的后续行动（如有）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resolveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResolve">确认解除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailsDialogVisible" :title="currentTask.title" width="60%">
      <div class="task-details-content" v-if="currentTask">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="任务ID">{{ currentTask.id }}</el-descriptions-item>
            <el-descriptions-item label="所属项目">{{ currentTask.project }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ currentTask.assignee }}</el-descriptions-item>
            <el-descriptions-item label="阻塞类型">
              <el-tag :type="getBlockTypeColor(currentTask.blockType)" effect="dark">
                {{ getBlockTypeText(currentTask.blockType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="阻塞时间">{{ formatDate(currentTask.blockDate) }}</el-descriptions-item>
            <el-descriptions-item label="已阻塞">{{ currentTask.blockDuration }}天</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(currentTask.priority)">
                {{ currentTask.priority }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="截止日期">{{ formatDate(currentTask.dueDate) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h3>阻塞详情</h3>
          <p class="block-reason">{{ currentTask.blockReason }}</p>
          
          <div v-if="currentTask.blockType === 'dependency'" class="dependency-info">
            <h4>依赖任务</h4>
            <el-table :data="currentTask.dependencies || []" style="width: 100%">
              <el-table-column prop="id" label="任务ID" width="80" />
              <el-table-column prop="title" label="任务名称" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="estimatedCompletion" label="预计完成时间" />
            </el-table>
          </div>
        </div>

        <div class="detail-section">
          <h3>处理历史</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(action, index) in currentTask.actions"
              :key="index"
              :timestamp="formatDateTime(action.time)"
              :type="action.type"
            >
              <h4>{{ action.title }}</h4>
              <p>{{ action.description }}</p>
              <p v-if="action.user"><strong>操作人：</strong> {{ action.user }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'BlockedTasks',
  components: {
    Search
  },
  setup() {
    const router = useRouter()
    const tasks = ref([])
    const loading = ref(true)
    const error = ref(null)
    const resolveDialogVisible = ref(false)
    const detailsDialogVisible = ref(false)
    const currentTask = ref({})
    
    const stats = reactive({
      total: 0,
      highPriority: 0,
      longBlocked: 0,
      resolvedToday: 0
    })
    
    const filters = reactive({
      project: '',
      priority: '',
      blockType: '',
      search: ''
    })
    
    const resolveForm = reactive({
      solution: '',
      relatedUsers: [],
      nextSteps: ''
    })
    
    const projectOptions = ref([
      { value: '前端重构', label: '前端重构' },
      { value: '后端优化', label: '后端优化' },
      { value: '数据分析平台', label: '数据分析平台' },
      { value: '移动应用开发', label: '移动应用开发' }
    ])
    
    const userOptions = ref([
      { value: '张三', label: '张三' },
      { value: '李四', label: '李四' },
      { value: '王五', label: '王五' },
      { value: '赵六', label: '赵六' },
      { value: '钱七', label: '钱七' }
    ])
    
    const filteredTasks = computed(() => {
      return tasks.value.filter(task => {
        const projectMatch = !filters.project || task.project === filters.project
        const priorityMatch = !filters.priority || task.priority === filters.priority
        const blockTypeMatch = !filters.blockType || task.blockType === filters.blockType
        const searchMatch = !filters.search || 
          task.title.toLowerCase().includes(filters.search.toLowerCase()) ||
          task.blockReason.toLowerCase().includes(filters.search.toLowerCase())
        
        return projectMatch && priorityMatch && blockTypeMatch && searchMatch
      })
    })

    const fetchBlockedTasks = async () => {
      try {
        loading.value = true
        // 这里替换为实际的 API 调用
        // const response = await fetch('/api/tasks/blocked')
        // tasks.value = await response.json()
        
        // 模拟数据
        setTimeout(() => {
          tasks.value = [
            {
              id: 'T-1001',
              title: '用户认证模块重构',
              project: '前端重构',
              assignee: '张三',
              priority: '高',
              blockType: 'technical',
              blockReason: '认证库存在兼容性问题，需要等待库作者修复或寻找替代方案',
              blockDate: '2024-05-01',
              blockDuration: 14,
              dueDate: '2024-05-25',
              dependencies: [],
              actions: [
                {
                  title: '问题报告',
                  description: '发现认证库与新版浏览器不兼容',
                  time: '2024-05-01T10:30:00',
                  user: '张三',
                  type: 'danger'
                },
                {
                  title: '问题分析',
                  description: '确认问题出在库的核心算法，已联系库作者',
                  time: '2024-05-02T14:15:00',
                  user: '李四',
                  type: 'warning'
                },
                {
                  title: '临时方案探讨',
                  description: '团队讨论了可能的临时解决方案，但都有较大缺陷',
                  time: '2024-05-05T11:00:00',
                  user: '王五',
                  type: 'info'
                }
              ]
            },
            {
              id: 'T-1023',
              title: '数据可视化组件实现',
              project: '数据分析平台',
              assignee: '李四',
              priority: '高',
              blockType: 'dependency',
              blockReason: '依赖的数据处理API尚未完成',
              blockDate: '2024-05-05',
              blockDuration: 10,
              dueDate: '2024-05-20',
              dependencies: [
                { id: 'T-985', title: '数据处理API开发', status: '进行中', estimatedCompletion: '2024-05-18' }
              ],
              actions: [
                {
                  title: '依赖问题记录',
                  description: '数据处理API尚未完成，无法继续进行可视化组件开发',
                  time: '2024-05-05T09:15:00',
                  user: '李四',
                  type: 'warning'
                },
                {
                  title: '沟通协调',
                  description: '与后端团队沟通，确认API开发计划',
                  time: '2024-05-06T15:30:00',
                  user: '李四',
                  type: 'info'
                }
              ]
            },
            {
              id: 'T-1045',
              title: '性能优化方案实施',
              project: '后端优化',
              assignee: '王五',
              priority: '中',
              blockType: 'decision',
              blockReason: '优化方案存在争议，需要管理层决策最终采用哪种方案',
              blockDate: '2024-05-08',
              blockDuration: 7,
              dueDate: '2024-05-22',
              dependencies: [],
              actions: [
                {
                  title: '方案争议记录',
                  description: '团队内对采用微服务还是单体架构优化存在分歧',
                  time: '2024-05-08T16:00:00',
                  user: '王五',
                  type: 'warning'
                },
                {
                  title: '方案对比文档',
                  description: '完成了两种方案的详细对比分析文档',
                  time: '2024-05-10T14:20:00',
                  user: '王五',
                  type: 'info'
                },
                {
                  title: '上报决策',
                  description: '已将对比文档提交给管理层，等待最终决策',
                  time: '2024-05-12T09:45:00',
                  user: '赵六',
                  type: 'info'
                }
              ]
            },
            {
              id: 'T-1056',
              title: '移动端适配',
              project: '移动应用开发',
              assignee: '赵六',
              priority: '低',
              blockType: 'resource',
              blockReason: '缺少测试设备，无法验证在特定型号手机上的表现',
              blockDate: '2024-05-12',
              blockDuration: 3,
              dueDate: '2024-05-30',
              dependencies: [],
              actions: [
                {
                  title: '资源问题记录',
                  description: '需要iPhone 15和小米14测试设备，已提交申请',
                  time: '2024-05-12T10:15:00',
                  user: '赵六',
                  type: 'warning'
                }
              ]
            },
            {
              id: 'T-1062',
              title: 'AI推荐算法集成',
              project: '数据分析平台',
              assignee: '钱七',
              priority: '高',
              blockType: 'technical',
              blockReason: '算法模型训练失败，需要重新调整参数和数据集',
              blockDate: '2024-05-10',
              blockDuration: 5,
              dueDate: '2024-05-28',
              dependencies: [],
              actions: [
                {
                  title: '训练失败记录',
                  description: '模型在大数据集上训练时发生过拟合',
                  time: '2024-05-10T17:30:00',
                  user: '钱七',
                  type: 'danger'
                },
                {
                  title: '参数调整尝试',
                  description: '尝试了多组参数，但效果仍不理想',
                  time: '2024-05-12T11:40:00',
                  user: '钱七',
                  type: 'info'
                },
                {
                  title: '专家咨询',
                  description: '联系了算法专家寻求帮助，等待回复',
                  time: '2024-05-14T09:20:00',
                  user: '钱七',
                  type: 'info'
                }
              ]
            }
          ]
          
          // 计算统计数据
          stats.total = tasks.value.length
          stats.highPriority = tasks.value.filter(task => task.priority === '高').length
          stats.longBlocked = tasks.value.filter(task => task.blockDuration >= 7).length
          stats.resolvedToday = 2  // 模拟数据
          
          loading.value = false
        }, 1000)
      } catch (err) {
        error.value = '获取阻塞任务数据失败'
        loading.value = false
        console.error(err)
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }

    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    }

    const getPriorityType = (priority) => {
      switch (priority) {
        case '高':
          return 'danger'
        case '中':
          return 'warning'
        case '低':
          return 'info'
        default:
          return 'info'
      }
    }

    const getBlockTypeColor = (type) => {
      switch (type) {
        case 'dependency':
          return 'warning'
        case 'resource':
          return 'info'
        case 'technical':
          return 'danger'
        case 'decision':
          return 'primary'
        case 'other':
          return 'success'
        default:
          return 'info'
      }
    }

    const getBlockTypeText = (type) => {
      switch (type) {
        case 'dependency':
          return '依赖'
        case 'resource':
          return '资源'
        case 'technical':
          return '技术'
        case 'decision':
          return '决策'
        case 'other':
          return '其他'
        default:
          return '未知'
      }
    }

    const getStatusType = (status) => {
      switch (status) {
        case '已完成':
          return 'success'
        case '进行中':
          return 'primary'
        case '未开始':
          return 'info'
        case '延期':
          return 'warning'
        case '阻塞':
          return 'danger'
        default:
          return 'info'
      }
    }

    const getDurationClass = (duration) => {
      if (duration >= 14) return 'duration-critical'
      if (duration >= 7) return 'duration-warning'
      return 'duration-normal'
    }

    const resolveTask = (task) => {
      currentTask.value = task
      resolveDialogVisible.value = true
      // 重置表单
      resolveForm.solution = ''
      resolveForm.relatedUsers = []
      resolveForm.nextSteps = ''
    }

    const submitResolve = () => {
      if (!resolveForm.solution) {
        ElMessage.warning('请填写解决方案')
        return
      }

      // 实际应用中应调用 API 来解除阻塞
      // 模拟解除阻塞
      const index = tasks.value.findIndex(t => t.id === currentTask.value.id)
      if (index !== -1) {
        tasks.value.splice(index, 1)
        stats.total--
        if (currentTask.value.priority === '高') {
          stats.highPriority--
        }
        if (currentTask.value.blockDuration >= 7) {
          stats.longBlocked--
        }
        stats.resolvedToday++
      }

      ElMessage.success(`任务 ${currentTask.value.title} 已解除阻塞`)
      resolveDialogVisible.value = false
    }

    const viewDetails = (task) => {
      currentTask.value = task
      detailsDialogVisible.value = true
    }

    onMounted(() => {
      fetchBlockedTasks()
    })

    return {
      tasks,
      loading,
      error,
      stats,
      filters,
      filteredTasks,
      projectOptions,
      userOptions,
      resolveDialogVisible,
      detailsDialogVisible,
      currentTask,
      resolveForm,
      formatDate,
      formatDateTime,
      getPriorityType,
      getBlockTypeColor,
      getBlockTypeText,
      getStatusType,
      getDurationClass,
      resolveTask,
      submitResolve,
      viewDetails,
      Search
    }
  }
}
</script>

<style scoped>
.blocked-tasks-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.filter-row {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 15px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.high-priority .stat-value {
  color: #f56c6c;
}

.long-blocked .stat-value {
  color: #e6a23c;
}

.resolved-today .stat-value {
  color: #67c23a;
}

.tasks-table {
  margin-top: 20px;
}

.task-link {
  color: #409eff;
  text-decoration: none;
}

.task-link:hover {
  text-decoration: underline;
}

.duration-normal {
  color: #909399;
}

.duration-warning {
  color: #e6a23c;
  font-weight: bold;
}

.duration-critical {
  color: #f56c6c;
  font-weight: bold;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h3 {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 500;
}

.detail-section h4 {
  margin: 10px 0;
  font-size: 16px;
  font-weight: 500;
}

.block-reason {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
  line-height: 1.6;
}

.dependency-info {
  margin-top: 15px;
}

.loading-container,
.error-container {
  margin: 30px 0;
}
</style> 